
package com.tools.cleanmaster.scenenew;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.appinfo.AppInfoCompat;
import com.tools.cleanmaster.appinfo.AppManagerCompat;
import com.tools.cleanmaster.taskmain.AppTaskUtils;
import com.tools.cleanmaster.taskmain.ProcessItem;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.FileHelper;
import com.tools.cleanmaster.utils.MemoryUtils;

import java.util.HashMap;
import java.util.List;

/**
 * 场景工具类
 */
public class SceneToolkit {

    /**
     * @return 运行进程数量
     * 耗时操作，不要在UI线程执行
     */
    public static int calcRunningTaskNum() {
        return getRunningTasks().size();
    }

    public static List<ProcessItem> getRunningTasks() {
        HashMap<String, ProcessItem> processMap = new HashMap<String, ProcessItem>();
        Context context = CleanApplication.getInstance();
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        return AppTaskUtils.getRunningTaskList(context, manager, processMap, false, false, null);
    }

    /**
     * @return 内存使用百分比 * 100
     */
    public static int calcMemoryUsedPercent() {
        int[] memoryInfo = MemoryUtils.getSystemMemory();
        int total = memoryInfo[1];
        int used = memoryInfo[1] - memoryInfo[0];
        int percent = (int) (used * 1f / (total > 0 ? total : 1) * 100);
        return percent;
    }


    public static boolean isBattery(String pkg) {

        return false;
    }

    public static boolean isDefaultProtected(String pkgName) {
        // 过滤省电
        if (isBattery(pkgName)) {
            return true;
        }
        // 过滤ducleaner
        return TextUtils.equals(pkgName, SceneConstants.CLEANER_PKG_NAME);
    }

    /**
     * 通过包名获取应用程序名称
     *
     * @return appName
     */
    public static String getAppNameByPackageName(String pkgName) {
        String appName = "";
        try {
            AppInfoCompat appInfo = AppManagerCompat.getAppInfo(pkgName);
            appName = appInfo.getLabel();
        } catch (PackageManager.NameNotFoundException e) {
            if (FeatureConfig.DEBUG_LOG) {
                e.printStackTrace();
            }
        }
        return appName;
    }

    public static SceneType getCurrentAplusScene(Context context) {
        /*if (!PackageUtils.isAppInstalled(context, CleanConstant.PKG_NAME_BOOSTER)) {
            SceneType.BAT_SHARPDEC.priority = ScenePriority.A;
            SceneType.BG_CPU_OVERLOAD.priority = ScenePriority.A_PLUS;
            return SceneType.BG_CPU_OVERLOAD;
        } else if (!PackageUtils.isAppInstalled(context, CleanConstant.PKG_NAME_BATTERY)) {
            SceneType.BAT_SHARPDEC.priority = ScenePriority.A_PLUS;
            SceneType.BG_CPU_OVERLOAD.priority = ScenePriority.A;
            return SceneType.BAT_SHARPDEC;
        }*/
        return null;
    }

    public static int sLastCpuIdle;
    public static int sLastCpuAll;
    public static int calculateCpu() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            return 0;
        }

        String statstr = null;
        try {
            // bug[pasta]: java.lang.ArrayIndexOutOfBoundsException, java.io.BufferedReader.readLine(BufferedReader.java:358)
            statstr = FileHelper.readFileAsString("/proc/stat");
        } catch (Exception e) {
            return 0;
        }
        if (statstr == null) {
            return 0;
        }
        String strcpu1 = null;
        try {
            String[] lines = statstr.split("\n");
            for (String line : lines) {
                if (line.startsWith("cpu ")) {
                    strcpu1 = line;
                }
            }
        } catch (Exception e) {
        }
        if (strcpu1 == null) return 0;
        int user, nice, system, idle;
        try {
            //strcpu1: cpu  42631 7015 15814 210479 4041 0 84 0 0 0
            String[] strArr = strcpu1.split("\\s+");
            user = Integer.parseInt(strArr[1]);
            nice = Integer.parseInt(strArr[2]);
            system = Integer.parseInt(strArr[3]);
            idle = Integer.parseInt(strArr[4]);
        } catch (Exception e) {
            return 0;
        }

        // 获取上次快照并计算CPU频率
        int cpuAll = user + nice + system + idle;
        int idl = idle - sLastCpuIdle;
        int totalCpuTime = cpuAll - sLastCpuAll;
        sLastCpuIdle = idle;
        sLastCpuAll = cpuAll;
        // 计算CPU频率
        float cpuUsage = 0;
        if (totalCpuTime > 0) {
            cpuUsage = 100 * (totalCpuTime - idl) / totalCpuTime;
        }
        // cpuUsgae强制小于100
        if(cpuUsage > 100) {
            cpuUsage = (float)(10 * Math.random()) + 90;
        }
        return (int) cpuUsage;
    }
}
